package com.zhiwei.msf.common.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhiwei_yang
 * @time 2021-2-5-11:14
 */
@Component
@Aspect
@Slf4j
public class RequestInterceptor {

    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.PostMapping) || " +
            "@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void pointCut() {
    }

    @Around("pointCut()")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        List<Object> params = new ArrayList<>();
        if (ArrayUtils.isNotEmpty(args)) {
            for (Object param : args) {
                if (param instanceof HttpServletRequest ||
                        param instanceof HttpServletResponse |
                                param instanceof HttpSession) {
                    continue;
                }
                params.add(param);
            }
        }
        Object result = joinPoint.proceed(args);
        log.info("[{}#{}]方法请求参数:{},响应:{}", joinPoint.getSignature().getDeclaringType().getSimpleName(),
                joinPoint.getSignature().getName(), JSON.toJSONString(params), JSON.toJSONString(result));
        return result;
    }
}